import router from '@/router'
import Vue from 'vue'
import { Toast } from 'vant'
import api from 'api'
import moment from 'moment'
import store from 'store'
import config from 'api/config.js'

Vue.use(Toast)

export default{
  namespaced:true,
  state:{
    userInfo:null,
  },
  mutations:{
    save_userInfo(state){
      let userInfo = sessionStorage.getItem("userInfo")
      if(userInfo && !state.userInfo){
        state.userInfo = JSON.parse(userInfo)
      }
    },
    change_member(state,params){
      state.userInfo.member.avatar = params.avatar
      state.userInfo.member.nickname = params.nickname
      sessionStorage.setItem("userInfo",JSON.stringify(state.userInfo))
    },
    outLogin(state){
      let userInfo = null
      state.userInfo = JSON.parse(JSON.stringify(userInfo))
      router.push(config.routerUrl+"/login")
    }
  },
  actions:{
    checkLogin(context){
      // console.log("checkLogin",context.state.userInfo)
      if(context.state.userInfo == null){
        Toast.fail('未登入')
        store.state.common.footerShow = false
        return router.push(config.routerUrl+'/login')
      }
    },
    // checkLogin(context){
    //   // let userInfo = sessionStorage.getItem("userInfo")
    //   let userInfo = context.state.userInfo
    //   if(userInfo){
    //     let time = Math.floor(moment().valueOf()/1000)
    //     console.log("checkLogin",time,userInfo.expiretime)
    //     if(time <= userInfo.expiretime){
    //       context.state.userInfo = userInfo
    //       return true;
    //     }else{
    //       Toast.fail('登入过期')
    //       return router.push('/login')
    //     }
    //   }
    //   Toast.fail('未登入')
    //   return router.push('/login')
    // },
    login(context,params){
      let loading = Toast.loading("登入中")
      api.post('/index/login ',params).then(e=>{
        context.state.userInfo = e.data
        context.state.userInfo.account = params.account
        e.data.member.always_check = 1
        e.data.member.check = 1
        let my = {
          // always_check:1,
          check:true,
          telphone:e.data.member.account,
          name:e.data.member.nickname!=''?e.data.member.nickname:'用户_'+e.data.member.account
        }
        store.commit("yuding/reloadPlayer",[my]) //把自己添加进打球人
        // context.state.userInfo.is_vip = 1
        sessionStorage.setItem("userInfo",JSON.stringify(e.data))
        loading.clear()
        Toast.success({message:'登入成功',duration:800})
        setTimeout(() => {
          router.push(config.routerUrl+"/user")
        }, 800);
      })
    }
  }
}